package com.jrx.anytxn.param.job.autoPaymentStatus;

import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnRuntimeException;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.base.BtBatchStatusMapper;
import com.jrx.anytxn.param.mapper.ext.ExtBtBatchStatusMapper;
import com.jrx.anytxn.param.mapper.ext.ExtPrOrganizationTableMapper;
import com.jrx.anytxn.param.config.AnytxnBatchProperties;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 批扣开始
 *
 * @author : zhenghaopu
 * 2019/11/23
 */
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class AutoPaymentStartConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(AutoPaymentStartConfiguration.class);


    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Resource
    private ExtPrOrganizationTableMapper extPrOrganizationTableMapper;

    @Resource
    private BtBatchStatusMapper btBatchStatusMapper;

    @Resource
    private ExtBtBatchStatusMapper extBtBatchStatusMapper;

    @Autowired
    private ISegmentService segmentService;

    @Bean
    public Job autoPaymentStartJob() {
        return jobBuilderFactory.get("autoPaymentStartJob")
                .start(autoPaymentStartStep())
                .build();
    }

    @Bean
    public Step autoPaymentStartStep() {
        return stepBuilderFactory.get("autoPaymentStartStep")
                .tasklet(autoPaymentStartTasklet())
                .build();
    }

    @Bean
    public Tasklet autoPaymentStartTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.info("批扣开始");
            //获取业务日期
            PrOrganizationTable org =
                    extPrOrganizationTableMapper.selectByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            //查询批次状态表
            List<String> statusList = Arrays.asList(Constant.BATCH_SATTUS_0,Constant.BATCH_SATTUS_1);
            List<BtBatchStatus> batchStatusList =
                    extBtBatchStatusMapper.selectByBusinessDateAndStatusForBatch(org.getNextProcessingDate(),
                            statusList,Constant.AUTO_PAYMENT,org.getTenantId());
            //若已经存在正在执行的任务 直接抛出异常
            if(CollectionUtils.isNotEmpty(batchStatusList)){
                String errMsg = String.format(ErrorMsgConstant.AUTO_PAYMENT_RUNNING,
                        batchStatusList.get(0).getBatchStatus());
                throw new TxnRuntimeException(errMsg);
            }else{//不存在正在执行的任务 插入任务数据 开始执行任务
                BtBatchStatus btBatchStatus = new BtBatchStatus();
                try {
                    btBatchStatus.setId(segmentService.getId(Constant.BT_BATCH_STATUS_ID));//id
                } catch (SegmentException e) {
                    logger.error("主键生成错误", e);
                    throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
                }
                btBatchStatus.setBatchStatus(Constant.BATCH_SATTUS_0);//状态 0 待执行
                btBatchStatus.setBusinessDate(org.getNextProcessingDate());//当前业务日期
                btBatchStatus.setJobName(Constant.AUTO_PAYMENT);//批处理名称
                btBatchStatus.setTenantId(org.getTenantId());//租户id
                btBatchStatus.setUpdateBy(Constant.DEFAULT_USER);
                btBatchStatus.setRecordVersionNumber(Constant.VERSION_NUMBER);//初始版本号
                btBatchStatusMapper.insertSelective(btBatchStatus);
            }
            return RepeatStatus.FINISHED;
        };
    }
}
